<template>
  <a-card :bordered="false" title="销售业绩" :body-style="{padding: 8}" :head-style="{fontSize: '18px'}">
    <template #extra>
      <a-space size="middle" class="analysis-tabs-extra">

        <a-select
          v-if="user.roleId !== '3' && user.roleId !== '4'"
          v-model:value="salesPerformanceSearch.agentId"
          :placeholder="user.selectPre+'全体代理商'"
          @change="reloadSalesPerformanceAgent"
          allowClear
        >
          <a-select-option v-for="agent in agentList2" :key="agent.id" :value="agent.id">
            {{ agent.name }}
          </a-select-option>
        </a-select>

        <a-select v-model:value="salesPerformanceSearch.selectUserId"
                  placeholder="全体销售"
                  @change="reloadSalesPerformanceUser"
                  allowClear
        >
          <a-select-option v-for="agentUser in agentUserList2" :key="agentUser.userId" :value="agentUser.userId">
            {{ agentUser.realName }}
          </a-select-option>
        </a-select>

        <!--导出Excel-->
        <a-button
          v-if="user.roleId !== '3' && user.roleId !== '4'&& user.roleId !== '5'"
          @click="exportExcel" type="primary"
          style="background-color: rgb(254,108,17);border:rgb(254,108,17);">
          <template #icon>
            <DownloadOutlined />
          </template>
          导出
        </a-button>

      </a-space>
    </template>

    <a-row :gutter="16">
      <a-col :lg="12" :md="24" :sm="24" :xs="24">
        <div>
          <a-table row-key="month"
                   size="middle"
                   :bordered="true"
                   :columns="salesPerformanceColumns"
                   :data-source="salesPerformanceData"
                   :pagination="false" />
        </div>
      </a-col>
      <a-col :lg="12" :md="24" :sm="24" :xs="24">
        <div>
          <ele-chart :options="saleOption" style="height: 350px;" />
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import EleChart from 'ele-admin-pro/packages/ele-chart';
import {} from '@ant-design/icons-vue';
import { DashboardApi } from '@/api/DashboardApi';
import { WebUserApi } from '@/api/WebUserApi';
import { utils, writeFile } from 'xlsx';

export default {
  name: 'AnalysisSales',
  components: {
    EleChart
  },
  props: {
    region: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // 用户信息
      user: {},
      // 销售业绩代理商列表
      agentList2: [],
      // 销售业绩代理商员工列表
      agentUserList2: [],
      // 销售业绩搜索参数
      salesPerformanceSearch: {
        region: null,
        selectUserId: null,
        agentId: null
      },
      // 销售业绩数据
      salesPerformanceData: [],
      salesPerformanceColumns: [
        {
          title: '月份',
          dataIndex: 'month',
          align: 'center',
          sorter: false
        },
        {
          title: '新增(件)',
          dataIndex: 'newCount',
          align: 'center',
          sorter: false
        },
        {
          title: '商谈中(件)',
          dataIndex: 'talkingCount',
          align: 'center',
          sorter: false
        },
        {
          title: () => (
            <div style="padding: 5px 10px;font-family: Arial, sans-serif;display: inline-block;">
              有效期临近(件)
              <span class="bubble-tip" style="margin-left: 10px;"><InfoCircleTwoTone /></span>
            </div>
          ),
          dataIndex: 'expirationCount',
          align: 'center',
          sorter: false
        },
        {
          title: '成交(件)',
          dataIndex: 'finishCount',
          align: 'center',
          sorter: false
        }
      ]
    };
  },
  computed: {
    saleOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['新报备件数', '客户商谈件数', '有效期临近件数', '成交件数'],
          orient: 'horizontal', // 水平布局
          right: 10,
          top: 0,
          // bottom: '-5', // 设置距离底部0像素
          left: 'center' // 居中对齐
        },
        xAxis: {
          data: this.salesPerformanceData.map(d => d.month)
        },
        yAxis: [
          {
            type: 'value',
            // 可以添加y轴的其他配置
          },
          {
            type: 'value',
            offset: -5,
            position: 'right',
            // 可以添加y轴的其他配置
          }
        ],
        // color: ['#24EB31', '#20C7FA', '#FC882D', '#910FF7'], // 颜色数组
        series: [
          {
            name: '新报备件数',
            data: this.salesPerformanceData.map(d => d.newCount),
            type: 'bar',
            yAxisIndex: 0,
            stack: 'x'
          },
          {
            name: '客户商谈件数',
            data: this.salesPerformanceData.map(d => d.talkingCount),
            type: 'bar',
            yAxisIndex: 0,
            stack: 'x'
          },
          {
            name: '有效期临近件数',
            data: this.salesPerformanceData.map(d => d.expirationCount),
            type: 'bar',
            yAxisIndex: 0,
            stack: 'x'
          },
          {
            name: '成交件数',
            data: this.salesPerformanceData.map(d => d.finishCount),
            type: 'line',
            stack: 'y',
            yAxisIndex: 1,
            symbolSize: 8 // 标记点的大小
          }
        ]
      };
    }
  },
  mounted() {
    this.getUser();
    this.getAgentList();
    this.getUser2();
    this.getSalesPerformanceData();
  },
  watch:{
    region() {
      console.log('刷新列表1');
      this.salesPerformanceSearch.region = this.region;
      this.reloadSalesPerformanceAgent();
      this.getAgentList();
    },
  },
  methods: {

    // 获取用户信息
    async getUser() {
      const res = await DashboardApi.getUser();
      this.user = res.data;
    },

    // 加载代理商下拉数据
    async getAgentList() {
      const res = await DashboardApi.findAgentList({region: this.salesPerformanceSearch.region});
      this.agentList2 = res.data;
    },

    // 获取用户信息
    async getUser2() {
      // 加载代理商员工列表
      const res = await WebUserApi.getAgentUserListByAgentId({ agentId: this.salesPerformanceSearch.agentId, region: this.salesPerformanceSearch.region });
      this.agentUserList2 = res.data;
    },

    /* 获取销售业绩数据 */
    async getSalesPerformanceData() {
      if(!this.salesPerformanceSearch.selectUserId){
        this.salesPerformanceSearch.selectUserId =null;
      }
      if(!this.salesPerformanceSearch.agentId){
        this.salesPerformanceSearch.agentId =null;
      }
      const res = await DashboardApi.salesPerformanceData(this.salesPerformanceSearch);
      this.salesPerformanceData = res.data;
    },
    async reloadSalesPerformanceAgent() {
      this.salesPerformanceSearch.selectUserId = null;
      this.getSalesPerformanceData();// 重新获取销售业绩数据
      this.getUser2();
    },
    async reloadSalesPerformanceUser() {
      this.getSalesPerformanceData();// 重新获取销售业绩数据
    },
    exportExcel() {
      this.loading = true;
      let array = [
        [
          '月份',
          '新报备件数',
          '客户商谈件数',
          '有效期临近件数',
          '成交件数'
        ]
      ];
      this.salesPerformanceData.forEach((d) => {
        array.push([
          d.month,
          d.newCount,
          d.talkingCount,
          d.expirationCount,
          d.finishCount
        ]);
      });
      writeFile(
        {
          SheetNames: ['销售业绩'],
          Sheets: {
            销售业绩: utils.aoa_to_sheet(array)
          }
        },
        '销售业绩.xlsx'
      );
      this.loading = false;
    }
  }
};
</script>

<style scoped>
/* 统计卡片 */
.analysis-chart-card :deep(.ant-card-body) {
  padding: 16px 22px 12px 22px;
}

.analysis-chart-card-num {
  font-size: 30px;
}

.analysis-chart-card-content {
  height: 40px;
}

.analysis-chart-card :deep(.ant-divider) {
  margin: 12px 0;
}

/* 销售额、访问量 */
.monitor-card-tabs :deep(.ant-tabs-bar) {
  padding: 0 16px 0 4px;
}

.monitor-card-tabs :deep(.ant-tabs-tab) {
  padding-left: 2px;
  padding-right: 2px;
  margin: 0 12px !important;
}

.monitor-card-tabs :deep(.ant-tabs-tabpane) {
  padding-bottom: 10px;
}

.demo-monitor-title {
  padding: 6px 20px;
}

.demo-monitor-rank-item {
  padding: 0 20px;
  margin-top: 18px;
}

@media screen and (max-width: 880px) {
  .analysis-tabs-extra {
    display: none;
  }
}
/* 表格斑马样式 **/
/deep/.ant-table-tbody tr:nth-child(2n)
{
  background-color:#fafafa;
}

/* 基础气泡样式 */
/deep/.bubble-tip {
  display: inline-block;
}

/* 气泡卡片内容 */
/deep/.bubble-tip::before {
  content: '报备有效期到期前30天'; /* 假设气泡内容通过data-content属性提供 */
  position: absolute;
  display: none;
  background-color: #333;
  color: #fff;
  padding: 5px 10px;
  border-radius: 5px;
  white-space: nowrap;
  z-index: 100;
  font-size: 12px;
  line-height: 1;
  box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.2);
}

/* 气泡箭头 */
/deep/.bubble-tip::after {
  content: "";
  position: absolute;
  display: none;
  border-style: solid;
  border-color: transparent;
}

/* 鼠标悬停时显示气泡 */
/deep/.bubble-tip:hover::before,
.bubble-tip:hover::after {
  display: block;
}

/* 气泡方向调整示例：假设向上弹出 */
/deep/.bubble-tip:hover::before {
  bottom: calc(100% + 5px); /* 调整气泡位置 */
  left: 75%;
  transform: translateX(-50%);
}

/deep/.bubble-tip:hover::after {
  bottom: calc(100% - 5px); /* 箭头位置 */
  left: 50%;
  border-width: 5px 5px 0;
  border-top-color: #333;
  transform: translateX(-50%) translateY(1px);
}
</style>
